package com.gome.cloud.web;

import com.gome.cloud.entity.User;
import com.gome.cloud.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author supan
 * @Date 2017/6/9 16:37
 * @Copyright(c) gome inc Gome Co.,LTD
 */
@RestController
public class ProviderController {
    private final Logger logger = LoggerFactory.getLogger(ProviderController.class);
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private UserRepository userRepository;
    /**
     * 简单计算接口
     * @param a
     * @param b
     * @return a+b
     */
    @RequestMapping(value = "/add" ,method = RequestMethod.GET)
    public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
        //List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        logger.info("server-provider--add()--方法被调用 参数a:{} 参数b:{}",a,b);
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return r;
    }
    /**
     * 根据id查询用户
     * @param id
     * @return User
     * @throws InterruptedException
     */
    @GetMapping("/user/{id}")
    public User findById(@PathVariable("id") Long id) throws InterruptedException {
//        //让线程等待几秒钟
//        int sleepTime = new Random().nextInt(3000);
//        logger.info("sleeptime: "+sleepTime);
//        Thread.sleep(sleepTime);
        User findOne = this.userRepository.findOne(id);
        logger.info("server-provider--findById()--方法被调用 参数id:{}",id);
        return findOne;
    }
    /**
     * 查询用户列表
     * @return
     */
    @GetMapping("/users")
    public List<User> findAll() {
        List<User> users = this.userRepository.findAll();
        logger.info("server-provider--findAll()--方法被调用 ");
        return users;
    }
    /**
     * 本地服务实例的信息
     * @return
     */
    @GetMapping("/info")
    public ServiceInstance showInfo() {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
        return localServiceInstance;
    }
    @RequestMapping(value= "/hello", method= RequestMethod.GET)
    public String index() {
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        logger.info("/hello, host:" + instance.getHost()+",service_id:"+instance.getServiceId());
        return "Hello World";
    }

}
